<template>
	<view>
		<button @click="generateKeyPair">生成密钥对</button>
		<button @click="encryptMessage">加密消息</button>
		<button @click="decryptMessage">解密消息</button>
		<p>公钥: {{ publicKey }}</p>
		<p>私钥: {{ privateKey }}</p>
		<p>加密消息: {{ encryptedMessage }}</p>
		<p>解密消息: {{ decryptedMessage }}</p>
		<view class="codeImg">
			<image v-if="shareImg != ''" :src="shareImg" mode="" class=""/>
		</view>
	</view>
</template>

<script>
	import QR from '../../components/qrcode/qrcode';
	import JSEncrypt from 'jsencrypt';

	export default {
		data() {
			return {
				privateKey: '',
				publicKey: '',
				encryptedMessage: '',
				decryptedMessage: '',
				invite: '0xc0f1fbf6199047f39f6DD49870124E073817BfBA',
				shareImg: '',
				shareUrl: '',
			};
		},
		onShow() {
			if(this.getQueryString('invite')){
				this.invite = this.getQueryString('invite');
			}
			console.log("invite:",this.invite);
		},
		methods: {
			generateKeyPair() {
				// 生成私钥和公钥
				// let key = new JSEncrypt.JSEncrypt();
				// encrypt.getKeypair(this.publicKey, this.privateKey);
				const encrypt = new JSEncrypt();
				encrypt.getKey(() => {
				  this.privateKey = encrypt.getPrivateKey();
				  this.publicKey = encrypt.getPublicKey();
				});
			},
			encryptMessage() {
				const encrypt = new JSEncrypt();
				encrypt.setPublicKey(this.publicKey);
				// const message = 'Hello, World!';
				const message = this.invite;
				console.log("message：",message);
				this.encryptedMessage = encrypt.encrypt(message);
				console.log("this.encryptedMessage：",this.encryptedMessage);
				this.shareUrl = 'http://localhost:8080/#/pages/index/jsencrypt?invite='+this.encryptedMessage;
				this.shareImg = this.creatQrcode(this.shareUrl);
			},
			decryptMessage() {
				const decrypt = new JSEncrypt();
				decrypt.setPrivateKey(this.privateKey);
				try {
					this.decryptedMessage = decrypt.decrypt(this.encryptedMessage);
				} catch (e) {
					console.error('Decryption failed', e);
				}
			},
			creatQrcode(url) {
				if (url == '') {
					return false;
				}
				let img = QR.createQrCodeImg(url);
				return img;
			}
		}
	};
</script>

<style scoped lang="scss">
	.codeImg{
		width: 200rpx;
		height: 200rpx;
		margin: auto;
		image{
			width: 100%;
			height: 100%;
			margin: auto;
		}
	}
</style>